package com.jcw.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcw.common.R;
import com.jcw.domain.ShoppingCart;
import com.jcw.service.ShoppingCartService;
import com.jcw.mapper.ShoppingCartMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author JCW
 * @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
 * @createDate 2023-03-30 11:19:16
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {

    @Resource
    private HttpSession session;

    @Override
    @Transactional
    public R<String> add(ShoppingCart shoppingCart) {
        Long userID = (Long) session.getAttribute("user");
        shoppingCart.setUserId(userID);
        ShoppingCart cart = query().eq("user_id", userID).eq("dish_id", shoppingCart.getDishId()).select("number").one();
        if (cart != null) {
            update().eq("user_id", userID).eq("dish_id", shoppingCart.getDishId()).set("number", cart.getNumber() + 1).update();
        } else {
            save(shoppingCart);
        }
        return R.success("添加成功");
    }

    @Override
    @Transactional
    public R<String> sub(ShoppingCart shoppingCart) {
        Long userID = (Long) session.getAttribute("user");
        ShoppingCart one = query().eq("user_id", userID)
                .eq(shoppingCart.getDishId() != null, "dish_id", shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, "setmeal_id", shoppingCart.getSetmealId()).select("number").one();

        if (one.getNumber()>1){
            update().eq("user_id", userID)
                    .eq(shoppingCart.getDishId() != null, "dish_id", shoppingCart.getDishId())
                    .eq(shoppingCart.getSetmealId() != null, "setmeal_id", shoppingCart.getSetmealId()).set("number",one.getNumber()-1).update();
        }else{
            update().eq("user_id", userID)
                    .eq(shoppingCart.getDishId() != null, "dish_id", shoppingCart.getDishId())
                    .eq(shoppingCart.getSetmealId() != null, "setmeal_id", shoppingCart.getSetmealId()).remove();
        }

        return R.success("商品减一");
    }

    @Override
    public R<String> clean() {
        Long userID = (Long) session.getAttribute("user");

        boolean removed = update().eq("user_id", userID).remove();
        if (removed){
            return R.success("清除成功");
        }
        return R.error("清除失败");
    }
}




